import type { LocaleType } from "#/config"

import { set } from 'lodash-es'

export const loadLocalePool: LocaleType[] = []


// 设置 HTML 页面的语言属性
export function setHtmlPageLang(locale: LocaleType) {
  document.querySelector('html')?.setAttribute('lang', locale)
}

export function setLoadLocalePool(cb: (loadLocalePool: LocaleType[]) => void) {
  cb(loadLocalePool)
}

// 返回以语言代码为键，对象包含具体的语言翻译为键的值
export function genMessage(langs: Record<string, Record<string, any>>, prefix = 'lang') {
  const obj: Recordable = {}

  Object.keys(langs).forEach(key => {
    const langFileMoudle = langs[key].default
    let fileName = key.replace(`./${prefix}/`, '').replace(/^\.\//, '')
    const lastIndex = fileName.lastIndexOf('.')
    fileName = fileName.substring(0, lastIndex)
    const keyList = fileName.split('/')
    const moduleName = keyList.shift()
    const objKey = keyList.join('.')

    if (moduleName) {
      if (objKey) {
        set(obj, moduleName, obj[moduleName] || {})
        set(obj[moduleName], objKey, langFileMoudle)
      } else {
        set(obj, moduleName, langFileMoudle || {})
      }
    }
  })
  return obj
}